package com.liao.domain.strategy.service.rule.filter.impl;

import com.liao.domain.strategy.model.entity.RuleActionEntity;
import com.liao.domain.strategy.model.entity.RuleMatterEntity;
import com.liao.domain.strategy.model.valobj.RuleLogicCheckTypeVO;
import com.liao.domain.strategy.repository.IStrategyRepository;
import com.liao.domain.strategy.service.annotation.LogicStrategy;
import com.liao.domain.strategy.service.rule.filter.ILogicFilter;
import com.liao.domain.strategy.service.rule.filter.factory.DefaultLogicFactory;
import com.liao.types.common.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;

/**
 * @Author long
 * @Description 【抽奖前规则】根据抽奖权重返回可抽奖范围KEY
 * @Date 2024-08-03 19:28
 */
@Slf4j
@Component
@LogicStrategy(logicMode = DefaultLogicFactory.LogicModel.RULE_WIGHT)
public class RuleWeightLogicFilter implements ILogicFilter<RuleActionEntity.RaffleBeforeEntity> {

    @Resource
    private IStrategyRepository strategyRepository;

    //模拟抽奖次数
    private Long userScore = 4500L;

    @Override
    public RuleActionEntity<RuleActionEntity.RaffleBeforeEntity> filter(RuleMatterEntity ruleMatterEntity) {
        log.info("规则过滤-权重范围 userId:{} strategyId:{} ruleModel:{}", ruleMatterEntity.getUserId(), ruleMatterEntity.getStrategyId(), ruleMatterEntity.getRuleModel());

        Long strategyId = ruleMatterEntity.getStrategyId();
        String ruleValue = strategyRepository.queryStrategyRuleValue(strategyId, ruleMatterEntity.getRuleModel(), ruleMatterEntity.getAwardId());

        Map<Long, String> analyticalValueGroup = getAnalyticalValue(ruleValue);

        if (analyticalValueGroup == null || analyticalValueGroup.isEmpty()) {
            return RuleActionEntity.<RuleActionEntity.RaffleBeforeEntity>builder()
                    .code(RuleLogicCheckTypeVO.ALLOW.getCode())
                    .info(RuleLogicCheckTypeVO.ALLOW.getInfo())
                    .build();
        }

        List<Long> userScoreList = new ArrayList<>(analyticalValueGroup.keySet());
        Collections.sort(userScoreList);

        Long preUserScore = null;
        for (Long l : userScoreList) {
            if (l <= userScore) {
                preUserScore = l;
            }else {
                break;
            }
        }
        if (preUserScore == null){
            //没有达到规定的最低积分，奖品的范围是全部奖品，随着积分消耗的增加，不同阶段对用的奖品不同
            return RuleActionEntity.<RuleActionEntity.RaffleBeforeEntity>builder()
                    .code(RuleLogicCheckTypeVO.ALLOW.getCode())
                    .info(RuleLogicCheckTypeVO.ALLOW.getInfo())
                    .build();
        }

        //获取到该用户对应存储在redis的抽奖规则
        String ruleWeightValueKey = analyticalValueGroup.get(preUserScore);
        return RuleActionEntity.<RuleActionEntity.RaffleBeforeEntity>builder()
                .ruleModel(DefaultLogicFactory.LogicModel.RULE_WIGHT.getCode())
                .data(RuleActionEntity.RaffleBeforeEntity.builder()
                        .ruleWeightValueKey(ruleWeightValueKey)
                        .strategyId(strategyId)
                        .build())
                .code(RuleLogicCheckTypeVO.TAKE_OVER.getCode())
                .info(RuleLogicCheckTypeVO.TAKE_OVER.getInfo())
                .build();
    }

    private Map<Long, String> getAnalyticalValue(String ruleValue) {
        String[] ruleValueGroups = ruleValue.split(Constants.SPACE);
        Map<Long, String> ruleValueMap = new HashMap<>();
        for (String ruleValueKey : ruleValueGroups) {
            // 检查输入是否为空
            if (ruleValueKey == null || ruleValueKey.isEmpty()) {
                return ruleValueMap;
            }
            // 分割字符串以获取键和值
            String[] parts = ruleValueKey.split(Constants.COLON);
            if (parts.length != 2) {
                throw new IllegalArgumentException("rule_weight rule_rule invalid input format" + ruleValueKey);
            }
            ruleValueMap.put(Long.parseLong(parts[0]), ruleValueKey);
        }
        return ruleValueMap;
    }

}
